<template xmlns="">
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

      <el-row :gutter="30">
        <el-col :span="6">
          <el-input placeholder="请输入内容" clearable @clear="getUsers" v-model="query.username">
            <el-button slot="append" icon="el-icon-search" @click="reload"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="openAddDialog">添加用户</el-button>
          <el-button type="primary" @click="batchDelete">批量删除</el-button>
        </el-col>

      </el-row>

      <el-table :data="userList" border stripe style="width: 100%" ref="moviesTable" @row-click="handleRowClick"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40">
        </el-table-column>
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>

        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state === 0"
              @change="changeDelete(scope.row)">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editUserDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>

            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" @click="assigningRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="query.current"
                     :page-size="query.size" :total="total" :page-sizes="[1, 2, 3, 50]"
                     layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

    </el-card>

    <!--      新增-->
    <el-dialog :close-on-click-modal="false"
               title="添加用户"
               :visible.sync="addDialog"
               @close="closeAddDialog">
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef"
               status-icon
               label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username" :disabled="!(id === '')"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="addForm.age"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" :loading="btnState" @click="addUser">确 定</el-button>
        <el-button @click="cancelAddDialog">取 消</el-button>
      </span>
    </el-dialog>

    <!--    分配权限-->
    <el-dialog :close-on-click-modal="false" @close="closeRoleDialog"
               title="分配权限"
               :visible.sync="roleDialog">
      <el-form :model="userRole" :rules="userRoleRule" ref="userRoleRef"
               status-icon
               label-width="100px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="userRole.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="rooleId">
          <el-select v-model="userRole.rooleId" clearable placeholder="请选择">
            <el-option
              v-for="item in allRoles" :key="item.id"
              :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <span slot="footer">
        <el-button type="primary" :loading="btnState" @click="saveOrUpdateRoleUser">确 定</el-button>
        <el-button @click="roleDialog = false">取 消</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
export default {
  name: 'User',
  data () {
    //自定义下拉规则
    var validateSelect = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }

    return {
      query: {
        username: '',
        current: 1,
        size: 2
      },
      userRole: {
        username: '',
        id: '',
        rooleId: '',
        userId: ''
      },
      allRoles: [{
        id: '',
        roleName: '请选择'
      }],
      //多选框选中的行的所有数据
      multipleSelection:[],
      selectIds:[],
      roleDialog: false,
      userList: [],
      total: 0,
      addDialog: false,
      id: '',
      btnState: false,
      addForm: {
        id: '',
        username: '',
        password: '',
        age: '',
        email: ''
      },
      addFormRule: {
        username: [{
          required: true,
          message: '用户名必填',
          trigger: 'blur'
        }, {
          min: 3,
          message: '用户名最少三位',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '用户密码必填',
          trigger: 'blur'
        }, {
          min: 6,
          max: 10,
          message: '密码在六到10位之间',
          trigger: 'blur'
        }],
        age: [{
          required: true,
          message: '年龄必填',
          trigger: 'blur'
        }, {
          type: 'number',
          message: '年龄必须为数字值',
          //trigger不写，则每个输入都验证
          trigger: 'blur'
        }],
        email: [{
          required: true,
          message: '邮箱必填',
          trigger: 'blur'
        }, {
          type: 'email',
          message: '请输入正确的邮箱地址',
          // trigger: ['blur', 'change']
          trigger: ['blur']
        }]

      },
      userRoleRule: {
        rooleId: [{
          required: true,
          message: '角色必选',
          trigger: 'blur'
        }, {
          validator: validateSelect,
          trigger: ['blur', 'change']
        }]
      }
    }
  },
  created () {
    this.reload()
    this.getRoles()
  },
  methods: {
    async reload () {
      this.query.current = 1
      this.query.size = 2
      await this.getUsers()
    },
    async getUsers () {
      const { data: res } = await this.$http.get('vueUser/user/list', { params: this.query })
      this.userList = res.result.records
      this.total = res.result.total
    },
    async getRoles () {
      const { data: res } = await this.$http.get('vueRole/allRoles')
      this.allRoles = this.allRoles.concat(res.result)
    },
    async changeDelete (row) {
      if (row.state === 0) {
        row.state = 1
      } else {
        row.state = 0
      }
      const { data: res } = await this.$http.post('vueUser/user/updateState', this.$Qs.stringify(row))
      if (res.success) {
        this.$message.success(res.message)
      }
    },
    handleSizeChange (val) {
      this.query.size = val
      this.getUsers()
    },
    handleCurrentChange (val) {
      this.query.current = val
      this.getUsers()
    },
    openAddDialog () {
      this.addDialog = !this.addDialog
      this.id = ''
    },
    addUser () {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          this.btnState = !this.btnState
          this.$http.post('vueUser/user/addUser', this.$Qs.stringify(this.addForm)).then(res => {
            if(!res.data.success){
              this.btnState = !this.btnState
              return  this.$message.error(res.data.message)
            }

            this.btnState = !this.btnState
            this.addDialog = !this.addDialog
            this.$message.success(res.data.message)
            this.reload()
          }).catch(err => {
            this.btnState = !this.btnState
            this.$message.error('操作失败')
          })
        }
      })
    },
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    cancelAddDialog () {
      this.$refs.addFormRef.resetFields()
      this.addForm = {}
      this.addDialog = !this.addDialog
    },
    async editUserDialog (id) {
      this.addDialog = !this.addDialog
      const { data: res } = await this.$http.get('vueUser/user/getUserById?id=' + id)
      this.addForm = res.result
      this.id = id
    },
    deleteUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'
            await this.$http.post('vueUser/user/deleteUser', this.$Qs.stringify({ id: id }))
            done()
            instance.confirmButtonLoading = false
            this.reload()
          } else {
            done()
          }
        }
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async assigningRoles (row) {
      const { data: res } = await this.$http.get('vueUser/user/getRoleId?id=' + row.id)
      if (res.result != null) {
        this.userRole.rooleId = res.result.rooleId
        this.userRole.id = res.result.id
      }
      this.userRole.userId = row.id
      this.userRole.username = row.username

      this.roleDialog = !this.roleDialog
    },
    async saveOrUpdateRoleUser () {
      await this.$refs.userRoleRef.validate(valid => {
          if (valid) {
            this.$http.post('vueUser/user/saveOrUpdateRoleUser', this.$Qs.stringify(this.userRole))
            this.roleDialog = !this.roleDialog
          }
        }
      )

    },
    closeRoleDialog () {
      this.$refs.userRoleRef.resetFields()
      this.userRole = {}
    },
    //复选框
    handleSelectionChange(val){
      this.multipleSelection = val
    },
    //修改所选行的选中状态
    handleRowClick(row){
      this.$refs.moviesTable.toggleRowSelection(row)
    },
    // 批量删除
    batchDelete(){
      if(this.multipleSelection.length === 0){
        return this.$message.error("未选择任何数据");
      }
      this.selectIds = this.multipleSelection.map(item => item.id)
      console.log(this.selectIds)
    }

  }

}
</script>

<style scoped>

</style>
